import { breadCrumbTypes } from "@/base-ui/breadCrumb/type/type"
import { RouteRecordRaw } from "vue-router"

const firstMenu: any = null
function mapMenuToRoutes(userMenu: any[]): RouteRecordRaw[] {
	const routes: RouteRecordRaw[] = []
	const allRoutes: RouteRecordRaw[] = []
	// const routeFiles = require.context('../router/main', true, /\.ts/)
	const routeFiles: any = import.meta.glob("../router/main/**/*.ts", {
		eager: true
	})
	for (const key in routeFiles) {
		allRoutes.push(routeFiles[key].default)
	}
	function _recurseGetRoute(menuList: any) {
		for (const menu of menuList) {
			if (menu.type === 2) {
				const route = allRoutes.find(item => {
					return item.path === menu.url
				})
				if (route) {
					routes.push(route)
				}
				// if (!firstMenu) {
				//   firstMenu = menu
				// }
			} else {
				_recurseGetRoute(menu.children)
			}
		}
	}
	_recurseGetRoute(userMenu)
	return routes
}

function mapHeaderBreadCrumb(menuList: any[], currPath: string) {
	let breadCrumbList: breadCrumbTypes[] | null = []
	// 数组扁平化 找到二级菜单
	// const menu = mapPathToMenu(menuList, currPath, breadCrumbList)
	// 把二级菜单和对应的一级菜单全部放到breadCrumbList中
	const menu = mapPathToMenu(menuList, currPath, breadCrumbList)
	if (!breadCrumbList.length && Object.keys(menu).length) {
		breadCrumbList.push(menu)
	}
	// breadCrumbList.push(menu)
	console.log("breadCrumbList", breadCrumbList)

	return breadCrumbList
}

function mapPathToMenu(menuList: any[], currPath: string, breadCrumb?: breadCrumbTypes[]) {
	for (const menu of menuList) {
		if (menu.type === 1) {
			const findMenu: any = mapPathToMenu(menu.children ?? [], currPath)
			console.log("findMenu", findMenu)

			if (findMenu) {
				breadCrumb?.push({ name: menu.name, id: menu.id })
				breadCrumb?.push({ name: findMenu.name, id: findMenu.id, path: findMenu.url })
				// menu 一级菜单  findMenu二级菜单
				// console.log("menu", menu)
				// console.log("findMenu", findMenu)
				return findMenu
			}
			if (!menu.children.length) {
				return menu
			}
		} else if (menu.type === 2 && menu.url === currPath) {
			return menu
		}
	}
}

export function menuMapLeafKeys(menuList: any[]) {
	const leftKeys: number[] = []

	const _recurseGetLeaf = (menuList: any[]) => {
		for (const menu of menuList) {
			if (menu.children) {
				_recurseGetLeaf(menu.children)
			} else {
				leftKeys.push(menu.id)
			}
		}
	}
	_recurseGetLeaf(menuList)

	return leftKeys
}

export function mapToAllRoutes() {
	const allRoutes: RouteRecordRaw[] = []
	// const routeFiles = require.context('../router/main', true, /\.ts/)
	const routeFiles: any = import.meta.glob("../router/main/**/*.ts", {
		eager: true
	})
	for (const key in routeFiles) {
		allRoutes.push(routeFiles[key].default)
	}
	return allRoutes
}

export { mapPathToMenu, mapMenuToRoutes, mapHeaderBreadCrumb, firstMenu }
